package com.d3works.apps.hr.db.repo;

import com.d3works.apps.hr.service.project.ProjectPlanningTimeService;
import com.d3works.apps.project.db.Project;
import com.d3works.apps.project.db.ProjectPlanningTime;
import com.d3works.apps.project.db.ProjectTask;
import com.d3works.apps.project.db.repo.ProjectPlanningTimeRepository;
import com.d3works.apps.project.db.repo.ProjectRepository;
import com.d3works.apps.project.db.repo.ProjectTaskRepository;
import com.google.inject.Inject;

public class ProjectPlanningTimeHRRepository extends ProjectPlanningTimeRepository {

  @Inject private ProjectPlanningTimeService planningTimeService;

  @Inject private ProjectRepository projectRepo;

  @Inject private ProjectTaskRepository projectTaskRepo;

  @Override
  public ProjectPlanningTime save(ProjectPlanningTime projectPlanningTime) {

    super.save(projectPlanningTime);

    Project project = projectPlanningTime.getProject();
    project.setTotalPlannedHrs(planningTimeService.getProjectPlannedHrs(project));

    Project parentProject = project.getParentProject();
    if (parentProject != null) {
      parentProject.setTotalPlannedHrs(planningTimeService.getProjectPlannedHrs(parentProject));
    }

    ProjectTask task = projectPlanningTime.getProjectTask();
    if (task != null) {
      task.setTotalPlannedHrs(planningTimeService.getTaskPlannedHrs(task));
    }

    return projectPlanningTime;
  }

  @Override
  public void remove(ProjectPlanningTime projectPlanningTime) {

    Project project = projectPlanningTime.getProject();
    ProjectTask task = projectPlanningTime.getProjectTask();

    super.remove(projectPlanningTime);

    if (task != null) {
      projectTaskRepo.save(task);
    } else {
      projectRepo.save(project);
    }
  }
}
